package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.VoiceVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class PeachblossomService {

  /*  //  接收文件，将文件上传到FastDFS，每个人每天能发送八次

    //表结构
    id， userid，voiceUri , created , listenmath,
    //将用户信息，及文件地址保存到monggo表内
    //用户信息只能被一人读取，添加进表内时设置一个属性值为true，被读取后改为false
    //没人一天只能读取十条语音，需要设置读取记录，没接收一次语音，在redis中存取*/
    @DubboReference
    private VoiceApi voiceApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;
    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private UserInfoApi userInfoApi;

    //保存上传的语音
    public Long save(MultipartFile soundFile) throws IOException {
        Long userId = UserHolder.getUserId();
        if(soundFile.isEmpty() ) {
            throw new BusinessException(ErrorResult.error());
        }
        //获取今日时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(new Date());

        //获取今日上传次数
        Long count = voiceApi.seelctCount(userId,format);
        if (count>= 10L){
            throw new BusinessException(ErrorResult.error());
        }

        //1、将音频上传到FastDFS,获取访问URL
        String filename = soundFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);
        String voiceUrl = webServer.getWebServerUrl() + storePath.getFullPath();


        //将数据添加到数据库中
        Voice voice = new Voice();
        voice.setCreated(System.currentTimeMillis());
        voice.setUserId(UserHolder.getUserId());
        voice.setVoiceUrl(voiceUrl);
        voice.setCreatDate(format);
        voice.setIsListen(true);

        Boolean b = voiceApi.save(voice);
        if (!b){
            throw new BusinessException(ErrorResult.error());
        }
        //返回上传次数
        return count;
    }

    //随机接收语音
    public VoiceVo getVoice() {
        Long userId1 = UserHolder.getUserId();
        //获取今日时间
        //获取今日时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(new Date());
        //判断自己查询的是第几次
        String key = Constants.VOICE_LISTEN_HASHKEY + userId1;
        Integer count = (Integer) redisTemplate.opsForHash().get(key, format);
        VoiceVo vo = new VoiceVo();

        if (count == null){
            //将昨天的reids查询数据删除

            //随机查询一个不是自己发送的语音
            Voice voice = voiceApi.selectRandom(userId1);
            //根据userid查询suerid
            Long userId = voice.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            //生成VoiceVo并返回
            vo= VoiceVo.init(userInfo, voice,9);
            redisTemplate.opsForHash().put(key,format,9);
        }else if (count == 0){
            throw new BusinessException(ErrorResult.error());
        } else {
            //随机查询一个不是自己发送的语音
            Voice voice = voiceApi.selectRandom(userId1);
            //根据userid查询suerid
            if (voice == null){
                throw new BusinessException(ErrorResult.error());
            }
            Long userId = voice.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            //count减一
            count = count-1;
            //删除原本的数据
            vo =  VoiceVo.init(userInfo,voice,count);
            redisTemplate.opsForHash().delete(key,format);
            redisTemplate.opsForHash().put(key,format,count);
        }

        return vo;
    }
}
